package com.chujian.framework.sync;

import cn.hutool.core.collection.CollUtil;
import com.chujian.framework.core.IId;
import com.chujian.framework.annotation.sync.EnableSync;

import java.util.Collection;

public class SyncDataFactory {
    /**
     * 构建单值的同步数据对象
     *
     * @param changeType 变更类型
     * @param service    service
     * @param item       item
     * @return SyncData
     */
    public static SyncData creSingleItemSyncData(String changeType, Object service, Object item) {
        if (null == item) return null;
        SyncData syncData = newSyncData(service, changeType);
        syncData.setDataId(((IId) item).getId())
                .setPayload(CollUtil.newArrayList(item));
        return syncData;
    }

    /**
     * 创建删除的同步数据对象
     *
     * @param service service
     * @param ids     ids
     * @return SyncData
     */
    public static SyncData creDeleteSyncData(Object service, Collection<?> ids) {
        if (CollUtil.isEmpty(ids)) return null;
        String idStr = CollUtil.join(ids, ",");
        SyncData syncData = newSyncData(service, SyncConst.CHANGE_TYPE_DELETE);
        syncData.setDataId(idStr)
                .setPayload(ids);
        return syncData;
    }

    /**
     * 创建SyncData对象
     *
     * @param service
     * @param changeType
     * @return
     */
    private static SyncData newSyncData(Object service, String changeType) {
        EnableSync enableSync = service.getClass().getAnnotation(EnableSync.class);
        String dataClass = enableSync.value().getSimpleName();
        SyncData syncData = new SyncData()
                .setSyncType("数据变更同步")
                .setChangeType(changeType);
        syncData.setCreTime(System.currentTimeMillis());
        syncData.setDataMark(dataClass);
        return syncData;

    }
}
